package danran.dbapi.application;

import danran.dbapi.controller.TokenController;
import danran.dbapi.filter.ApiFilter;
import danran.dbapi.plugin.PluginConf;
import danran.dbapi.plugin.loader.PluginClassLoader;
import danran.dbapi.servlet.APIServlet;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;
import java.util.ArrayList;

/**
 * @Classname DBAPIApplication
 * @Description TODO
 * @Date 2022/1/17 17:32
 * @Created by RanCoder
 */
@SpringBootApplication(scanBasePackages = {"danran.dbapi"})
@EnableCaching
@MapperScan("danran.dbapi.mapper")
public class DBAPIApplication {
    public static void main(String[] args) {
        SpringApplication.run(DBAPIApplication.class, args);
    }

    @Autowired
    APIServlet apiServlet;

    @Autowired
    ApiFilter apiFilter;

    @Bean
    public ServletRegistrationBean getServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(apiServlet);
        bean.addUrlMappings("/api/*");
        return bean;
    }

    @Bean
    public FilterRegistrationBean getFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(apiFilter);
        ArrayList<String> urls = new ArrayList<>();
        urls.add("/api/*");//配置过滤规则
        registrationBean.setUrlPatterns(urls);
//        registrationBean.setOrder(3);
        return registrationBean;
    }

    @Bean({"PluginClassLoader"})
    public PluginClassLoader pluginClassLoader() {
        return new PluginClassLoader(PluginConf.getKey("plugin.targetPath"));
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxRequestSize(DataSize.parse("200MB"));
        factory.setMaxFileSize(DataSize.parse("200MB"));
        return factory.createMultipartConfig();
    }
}
